<?php
namespace app\controllers;

use Yii;
use app\common\ErrorCode;
use Pheanstalk\Pheanstalk;
use app\controllers\BaseController;
use app\models\GameUser;
use app\models\Morning;
use app\models\MorningRecord;

class MorningController extends BaseController
{
    public $enableCsrfValidation = false;
    public function actionGetup(){
        $getup = $this->Time();
        $second = $getup['second'];
        $msectime = $getup['msectime'];
        $datetime = $getup['datetime'];
        $time = $getup['time'];
        if( Yii::$app->request->isPost ){
            $postData = Yii::$app->request->post();
            $session = $postData['session'];
            $userdata = $this->judgeSession($session);
            if( !empty($userdata['code']) ){
                BaseController::sendClientId($client_id, $data);
                exit(0);
            }
            $userid = $userdata['id'];
            $nickname = $userdata['nickname'];
            $avatarurl = $userdata['avatarUrl'];

            //判断当前时间
            $nowtime = $this->JudgeTime($time);
            if( $nowtime != 1 ){
                $content = array(
                    'usersign' => false,
                    'nowtime' => $nowtime,
                );
                $data = array(
                    'code' => ErrorCode::$SUCCESS,
                    'code_info' => '成功',
                    'datatype' => '100',
                    'data' => $content,
                );
                BaseController::sendMessage($userid, json_encode($data));
                exit(0);
            }

            //检查redis是否有当天的签到记录
            $signkey = 'usersign.' . $userid . '=';
            $usersign = Yii::$app->redis->get($signkey);
            if( !empty($usersign) ){
                $content = "请不要重复点击";
                $data = array(
                    'code' => ErrorCode::$SUCCESS,
                    'code_info' => '成功',
                    'data' => $content,
                );
                BaseController::sendMessage($userid, json_encode($data));
                exit(0);
            }
            $redis = Yii::$app->redis->setex($signkey, $second, json_encode($time));

            //如果时间刚好在预定范围则开始签到
            $morningdata = Morning::data_by_id($userid);
            // 判断昨天签到
            $yetsign = $this->yesterdayWakeUpSign($userid);
            $signdata = array(
                'time' => $time,
                'onsign' => $morningdata['onsign'],
                'signdays' => $morningdata['signdays'],
                'totalscore' => $morningdata['totalscore'],
                'shopscore' => $morningdata['shopscore'],
                'yetsign' => $yetsign,
            );
            $signdata = $this->JudgeScore($signdata);
            $data = array(
                'userid' => $userid, //用户序号
                'nickname' => $nickname,
                'avatarurl' => $avatarurl, //头像
                'onsign' => $signdata['onsign'],//连续签到天数
                'signdays' => $signdata['signdays'], //签到天数
                'signscore' => $signdata['signscore'],//连签增加积分
                'totalscore' => $signdata['totalscore'], //总积分
                'shopscore' => $signdata['shopscore'],//商城积分
                'datetime' => $datetime,
                'time' => $time,
                'msectime' => $msectime,
                'score' => $signdata['score'],//获得积分
            );
            //beanstalkd有个pheanstalk的类可以处理工作的队列，用这个队列处理录入数据库的任务 同时先把用户的签到时间和分数返回客户端
            $proudcer = $this->inProducer($data);
            //sleep是为了让消费者能够及时录入消息
            sleep(1);
            //获取用户的具体签到数据
            $content = $this->getupContent($data);
            $key = 'signid:'.$userid;
            $redis = Yii::$app->redis->setex($key, $second, json_encode($content));
            //签到后更新首页的头像数据
            $groupid ='Getup-room';
            $lastten = Morning::LastTenbydatatime();
            $avatarurl = array(
                'avatarurl' => $avatarurl, 
            );
            $lastdata = array(
                'code' => ErrorCode::$SUCCESS,
                'code_info' => '成功',
                'datatype' => '101',
                'data' => $avatarurl,
            );
            //用户签到要发送数据
            $data = array(
                'code' => ErrorCode::$SUCCESS,
                'code_info' => '成功',
                'datatype' => '100',
                'data' => $content,
            );

            //用户发送消息
            BaseController::sendMessage($userid, json_encode($data));
            //组群发送消息
            BaseController::sendGroupId($groupid, json_encode($lastdata));
        }else{
            $content = "接收的posts数据为空";
            $data = array(
                '0' => -2,
                '1' => $content,
            );
            return BaseController::FailRespone($data);   
        }
        exit(0);
    }

    //测试待删函数Wakeup
    public function actionWakeup(){
        $getup = $this->Time();
        $second = $getup['second'];
        $msectime = $getup['msectime'];
        $datetime = $getup['datetime'];
        $time = $getup['time'];
        if( Yii::$app->request->isPost ){
            $postData = Yii::$app->request->post();
            $openid = $postData['openid'];
            $userdata = $this->judgeOpenid($openid);
            if( !empty($userdata['code']) ){
                BaseController::sendClientId($client_id, $data);
                exit(0);
            }
            $userid = $userdata['id'];
            $nickname = $userdata['nickname'];
            $avatarurl = $userdata['avatarUrl'];

            //判断当前时间
            $nowtime = $this->JudgeTime($time);
            if( $nowtime != 1 ){
                $content = array(
                    'usersign' => false,
                    'nowtime' => $nowtime,
                );
                $data = array(
                    'code' => ErrorCode::$SUCCESS,
                    'code_info' => '成功',
                    'datatype' => '100',
                    'data' => $content,
                );
                BaseController::sendMessage($userid, json_encode($data));
                exit(0);
            }

            //检查redis是否有当天的签到记录
            $signkey = 'usersign.' . $userid . '=';
            $usersign = Yii::$app->redis->get($signkey);
            if( !empty($usersign) ){
                $content = "请不要重复点击";
                $data = array(
                    'code' => ErrorCode::$SUCCESS,
                    'code_info' => '成功',
                    'data' => $content,
                );
                BaseController::sendMessage($userid, json_encode($data));
                exit(0);
            }
            $redis = Yii::$app->redis->setex($signkey, $second, json_encode($time));

            //如果时间刚好在预定范围则开始签到
            $morningdata = Morning::data_by_id($userid);
            // 判断昨天签到
            $yetsign = $this->yesterdayWakeUpSign($userid);
            $signdata = array(
                'time' => $time,
                'onsign' => $morningdata['onsign'],
                'signdays' => $morningdata['signdays'],
                'totalscore' => $morningdata['totalscore'],
                'shopscore' => $morningdata['shopscore'],
                'yetsign' => $yetsign,
            );
            $signdata = $this->JudgeScore($signdata);
            $data = array(
                'userid' => $userid, //用户序号
                'nickname' => $nickname,
                'avatarurl' => $avatarurl, //头像
                'onsign' => $signdata['onsign'],//连续签到天数
                'signdays' => $signdata['signdays'], //签到天数
                'signscore' => $signdata['signscore'],//连签增加积分
                'totalscore' => $signdata['totalscore'], //总积分
                'shopscore' => $signdata['shopscore'],//商城积分
                'datetime' => $datetime,
                'time' => $time,
                'msectime' => $msectime,
                'score' => $signdata['score'],//获得积分
            );
            //var_dump($data);
            //beanstalkd有个pheanstalk的类可以处理工作的队列，用这个队列处理录入数据库的任务 同时先把用户的签到时间和分数返回客户端
            $proudcer = $this->inProducer($data);
            //sleep是为了让消费者能够及时录入消息
            sleep(1);
            //获取用户的具体签到数据
            $content = $this->getupContent($data);
            $key = 'signid:'.$userid;
            $redis = Yii::$app->redis->setex($key, $second, json_encode($content));
            //签到后更新首页的头像数据
            $groupid ='Getup-room';
            $lastten = Morning::LastTenbydatatime();
            $avatarurl = array(
                'avatarurl' => $avatarurl, 
            );
            $lastdata = array(
                'code' => ErrorCode::$SUCCESS,
                'code_info' => '成功',
                'datatype' => '101',
                'data' => $avatarurl,
            );
            //用户签到要发送数据
            $data = array(
                'code' => ErrorCode::$SUCCESS,
                'code_info' => '成功',
                'datatype' => '100',
                'data' => $content,
            );

            //用户发送消息
            BaseController::sendMessage($userid, json_encode($data));
            //组群发送消息
            BaseController::sendGroupId($groupid, json_encode($lastdata));
        }else{
            $content = "接收的posts数据为空";
            $data = array(
                '0' => -2,
                '1' => $content,
            );
            return BaseController::FailRespone($data);   
        }
        exit(0);
    }

    public static function actionRedisdelete(){
        $result = Yii::$app->redis->get('usersign.' . '3314' . '=');
        var_dump($result);
        return $result;
    }

    public static function actionDelete(){
        $pheanstalk = new Pheanstalk('127.0.0.1', 11300 );
        $job = $pheanstalk->watch('wakeup')->reserve( 5 );
        if($job){
            var_dump($job);
            $pheanstalk->delete($job);
        }else{
            echo "No Jobs";
        }    
    }

    public function yesterdayWakeUpSign($userid){
    	$yetsign = MorningRecord::yesterdaySignup($userid);
    	if($yetsign){
    		$result = 1;
    	}else{
    		$result = -1;
    	}
        return $result;
    }

    public function inProducer($data){
    	$pheanstalk = new Pheanstalk( '127.0.0.1', 11300 );
		$tube = $pheanstalk->useTube('wakeup');
		$job = $tube->put(json_encode($data));
		if( !$job ){
			$job = -1;
		}
		return $job;
    }

    public function getupContent($data){
        $morning = new Morning();
        $record = new MorningRecord();
        $time = Morning::getMorningTime($data['userid']);
    	$scoreRank = $morning->getTotalScoreRank($data['totalscore'],$data['datetime'],$data['msectime']);
    	$getupRank = $morning->getMorningRank($time['time'],$time['msectime']);
    	date_default_timezone_set('Asia/Shanghai');
        //详细时间
        $week = date("w");
        $date = date("y/m/d");
        $weekarray = array("周日","周一","周二","周三","周四","周五","周六");
        $day = $weekarray[date("w")];
        $imgtime = explode(" ", $data['datetime']);
        $imgtime = explode("-", $imgtime[0]);
        $imgtime = $imgtime[0]. " ". "/". " ". $imgtime[1]. " ". "/". " ".$imgtime[2]. " "."/". " ". $day; 
        //是否在排行奖励中
        $rankin = 0;
        //获得什么
        $where = " ";
        $where1 = "-";
        $where2 = " ";
        $move = " ";
        $whatmove = " ";
        $get = "明天签到前十有惊喜哦~";
        $mget = " ";
        if( $week != 0 && $week != 6 ){
          if($getupRank <= 3 && $getupRank >= 1 ){
                  $where1 = "请在明天之内到四饭";
                  $where2 = "[青年包子铺]";
                  $get = "领取豆浆一份";
                  $whatmove = "(需提供昨天签到记录)";
                  $mget = "【前3奖励】获得豆浆一份";
                  $rankin = 1; 
          }
        }else{
            if($getupRank <= 3 && $getupRank >= 1){
               $where ="请在明天内到四饭";
               $where1 = "[青年包子铺]";
               $get = "领取豆浆一杯";
               $whatmove = "(需提供昨天签到记录)";
               $mget = "【前3奖励】获得豆浆一份";
               $rankin = 1;
           } 
    	}
        $rankin = 0; 
        $time = explode(':', $data['time']);
        $time = $time[0].':'.$time[1];
        $data = array(
            'usersign' => true,
            'userid' => $data['userid'],//用户ID
            'getupRank' => $getupRank,  //起床排名
            'imagetime' => $imgtime,    //图片合成时间
            'datetime' => $data['datetime'],//起床具体时间
            'weekday' => $week,         //具体日
            'time' => $time,            //时间
            'msectime' => $data['msectime'],    //精确时间
            'onsign' => $data['onsign'], //连续签到天数
            'signdays' => $data['signdays'],//签到天数
            'score' => $data['score'],  //获得积分
            'totalscore' => $data['totalscore'],//总分
            'scoreRank' => $scoreRank, //分数排名
            'where' => $where,
            'where1' => $where1,
            'where2' => $where2,
            'get' => $get, //拿什么
            'whatmove' => $whatmove,//证明
            'mget' => $mget, //奖励提醒
            'rankin' => $rankin, //是否进入奖励范围
            );
    	return $data;
    }

    public function alreadySignContent($data){
        $data = json_decode($data);
        $data = get_object_vars($data);
        $morning = new Morning();
        $record = new MorningRecord();
    	$scoreRank = $morning->getTotalScoreRank($data['totalscore'],$data['msectime']);
    	$getupRank = $record->getMorningRank($data['time'],$data['msectime']);
    	$tittle = "今天你已经签到了！";
    	$content = $tittle . "你是今天第" . $getupRank . "个起床的北鼻哦.\n\n";
    	$content = $content . "\n到".$data['time']."为止,\n已经连续签到".$data['signdays']."天,\n积分共有:".$data['totalscore']."分,\n积分排名:".$scoreRank."名.\n";
        $data = array(
            'getupRank' => $getupRank,
            'time' => $data['time'],
            'signdays' => $data['signdays'],
            'totalscore' => $data['totalscore'],
            'scoreRank' => $scoreRank,
            'content' => "你已经签到了"
            );
    	return $data;
    }


}

